import { Tsrv, ifs, vue } from '@/services';
import { Action, Module, Mutation, VuexModule } from 'vuex-module-decorators';

@Module
export default class App extends VuexModule {
  language: string = '';

  clipboard: string = '';

  sysInfo: any = {};

  layoutConfigs: any = {};

  funInfo: any = {};

  funConfigs: any = {};

  isMagicboxOpen: number = 0;

  modalCount: number = 0;

  sysMsgTips: any = {
    // 用于临时解决消息 不能响应式 的问题
    count: {
      config: {
        title: 'count',
        value: 999,
        count: {
          total: 0,
          unread: 0
        }
      },
      el: []
    }
    // count: {
    //   total: 0,
    //   unread: 0
    // }
  };

  sysMsgCount: any = {};

  unGlobalList: Array<string> = [];

  get SysInfo(): any {
    return this.sysInfo;
  }

  get Clipboard(): any {
    return this.clipboard;
  }

  get LayoutConfigs(): any {
    return this.layoutConfigs;
  }

  get FunConfigs(): any {
    return this.funConfigs;
  }

  get Language(): any {
    return this.language;
  }

  get IsMagicboxOpen(): any {
    return this.isMagicboxOpen;
  }

  get ModalCount(): any {
    return this.modalCount;
  }

  get SysMsgTips(): any {
    return this.sysMsgTips;
  }

  get SysMsgCount(): any {
    return this.sysMsgCount;
  }

  get FunInfo(): any {
    return this.funInfo;
  }

  get UnGlobalList(): Array<string> {
    return this.unGlobalList;
  }

  @Mutation
  SET_UNGOLBALLIST(val: any) {
    this.unGlobalList = val;
  }

  @Mutation
  SET_MODALCOUNT(val: number) {
    this.modalCount = val;
  }

  @Mutation
  ADD_MODALCOUNT() {
    ++this.modalCount;
  }

  @Mutation
  SET_ISMAGICBOXOPEN(val: number) {
    this.isMagicboxOpen = val;
  }

  @Mutation
  SET_SETLANGUAGE(lang: any) {
    this.language = lang;
  }

  @Mutation
  SET_SYSINFO(loadedSysInfo: any): any {
    this.sysInfo = loadedSysInfo;
  }

  @Mutation
  SET_CLIPBOARD(val: string): any {
    this.clipboard = val;
  }

  @Mutation
  SET_LAYOUTCONFIGS(config: any): any {
    this.layoutConfigs[config.key] = config.val;
  }

  @Mutation
  SET_FUNINFO(config: any): any {
    this.funInfo[config.key] = config.val;
  }

  @Mutation
  SET_FUNCONFIGS(config: any): any {
    this.funConfigs[config.key] = config.val;
  }

  @Mutation
  ADD_SYSMSGTIPS(data: any): any {
    const type = data.type;
    const category = data.category;
    const status = data.status;
    const updateCount = () => {
      const msgEl = this.sysMsgTips[type.key].el.find(
        ele => ele.title === category
      );
      if (Tsrv.noValue(msgEl)) {
        const newEl = {
          title: category,
          count: {
            total: 0,
            unread: 0
          }
        };
        if (status === 0) {
          newEl.count.unread += 1;
          this.sysMsgTips[type.key].config.count.unread += 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.unread += 1;
          // this.sysMsgTips.count.unread += 1;
        }
        if (status !== 2) {
          newEl.count.total += 1;
          this.sysMsgTips[type.key].config.count.total += 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.total += 1;
          // this.sysMsgTips.count.total += 1;
        }
        this.sysMsgTips[type.key].el.push(newEl);
      } else {
        if (status === 0) {
          msgEl.count.unread += 1;
          this.sysMsgTips[type.key].config.count.unread += 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.unread += 1;
          // this.sysMsgTips.count.unread += 1;
        }
        if (status !== 2) {
          msgEl.count.total += 1;
          this.sysMsgTips[type.key].config.count.total += 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.total += 1;
          // this.sysMsgTips.count.total += 1;
        }
      }
    };
    if (Tsrv.noValue(this.sysMsgTips[type.key])) {
      this.sysMsgTips[type.key] = {
        config: {
          title: type.key,
          value: type.value,
          count: {
            total: 0,
            unread: 0
          }
        },
        el: []
      };
      updateCount();
    } else {
      updateCount();
    }
  }

  @Mutation
  DEL_SYSMSGTIPS(data: any): any {
    const type = data.type;
    const category = data.category;
    const status = data.status;
    if (Tsrv.noValue(this.sysMsgTips[type.key])) {
      console.info(Tsrv.getI18nByValue('无此消息类型'));
    } else {
      const msgEl = this.sysMsgTips[type.key].el.find(
        ele => ele.title === category
      );
      if (Tsrv.noValue(msgEl)) {
        console.info(Tsrv.getI18nByValue('无此消息分类'));
      } else {
        if (status === 0) {
          msgEl.count.unread -= 1;
          this.sysMsgTips[type.key].config.count.unread -= 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.unread -= 1;
          // this.sysMsgTips.count.unread -= 1;
        }
        // 一：消息没有被软删除（已读和未读） - 总数 -1，二：未传入消息状态也默认删除的是已读消息 - 总数 -1
        if (status !== 2 || status === undefined) {
          msgEl.count.total -= 1;
          this.sysMsgTips[type.key].config.count.total -= 1;
          // 用于临时解决消息 不能响应式 的问题
          this.sysMsgTips.count.config.count.total -= 1;
          // this.sysMsgTips.count.total -= 1;
        }
      }
    }
  }

  @Mutation
  CLEAR_SYSMSGTIPS(): any {
    // this.sysMsgTips = { ...Object.assign(this.sysMsgTips, {}) };
    const msgTips = Object.keys(this.sysMsgTips);
    for (let i = 0; i < msgTips.length; i++) {
      if (msgTips[i] === 'count') {
        continue;
      }
      const ele = this.sysMsgTips[msgTips[i]];
      ele.config.count.unread = 0;
      if (ele.el.length > 0) {
        ele.el.forEach((e: any) => {
          e.count.unread = 0;
        });
      }
    }
    this.sysMsgTips['count'].config.count.unread = 0;
  }

  // sysMsgCount
  @Mutation
  ADD_SYSMSGCOUNT(typeACate: Array<string>): any {
    const [type, category, status] = typeACate;
    const updateCount = (t: string, c: string, s: string) => {
      if (Tsrv.noValue(this.sysMsgCount[type][category])) {
        this.sysMsgCount[type][category] = {
          total: 0,
          unread: 0
        };
        this.sysMsgCount[type][category][status] += 1;
      } else {
        this.sysMsgCount[type][category][status] += 1;
      }
    };
    if (Tsrv.noValue(this.sysMsgCount[type])) {
      this.sysMsgCount[type] = {};
      updateCount(type, category, status);
    } else {
      updateCount(type, category, status);
    }
  }

  @Mutation
  DEL_SYSMSGCOUNT(typeACate: Array<string>): any {
    const [type, category, status] = typeACate;
    if (
      !Tsrv.noValue(this.sysMsgCount[type]) &&
      !Tsrv.noValue(this.sysMsgCount[type][category])
    ) {
      this.sysMsgCount[type][category][status] -= 1;
      return;
    }
    // Tsrv..$msg(Tsrv.getI18nByValue('未获取主单ID'));
    console.error(Tsrv.getI18nByValue('查无此类性消息'));
  }

  @Mutation
  CLEAR_SYSMSGCOUNT(typeACate: Array<string>): any {
    const [type, category] = typeACate;
    if (
      !Tsrv.noValue(this.sysMsgCount[type]) &&
      !Tsrv.noValue(this.sysMsgCount[type][category])
    ) {
      this.sysMsgCount[type][category]['total'] = 0;
      this.sysMsgCount[type][category]['unread'] = 0;
      return;
    }
    // Tsrv..$msg(Tsrv.getI18nByValue('未获取主单ID'));
    console.error(Tsrv.getI18nByValue('查无此类性消息'));
  }

  @Action
  setModalCount(val: number): any {
    this.context.commit('SET_MODALCOUNT', val);
  }

  @Action
  addModalCount(): any {
    this.context.commit('ADD_MODALCOUNT');
  }

  @Action
  setSysInfo(loadedSysInfo: any): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.context.commit('SET_SYSINFO', loadedSysInfo);
      resolve(true);
    });
  }

  @Action
  setClipboard(val: string): any {
    this.context.commit('SET_CLIPBOARD', val);
  }

  @Action
  setLayoutConfigs(val: any): any {
    this.context.commit('SET_LAYOUTCONFIGS', {
      key: val.key,
      val: val.value
    });
  }

  @Action
  setFunInfo(val: any): any {
    this.context.commit('SET_FUNINFO', {
      key: val.key,
      val: val.value
    });
  }

  @Action
  setFunConfigs(val: any): any {
    this.context.commit('SET_FUNCONFIGS', {
      key: val.key,
      val: val.value
    });
  }

  @Action
  getLayoutConfigAsync(val: {
    funid: string;
    field: string;
    type: string;
  }): Promise<any> {
    const field: string = val.field;
    return new Promise(resolve => {
      if (field) {
        let flag = true;
        if (val.type === 'layout') {
          // 取缓存
          if (this.layoutConfigs[field] && this.layoutConfigs[field] !== null) {
            flag = false;
            resolve({
              current: this.layoutConfigs[field],
              all: this.layoutConfigs
            });
          }
        } else {
          if (this.funConfigs[field] && this.funConfigs[field] !== null) {
            flag = false;
            resolve({
              current: this.funConfigs[field],
              all: this.funConfigs
            });
          }
        }
        // 无缓存
        if (flag) {
          vue.prototype.$Loading.start();

          Tsrv.standardPostReq<ifs.I_getFunConfRes, any>(
            { funName: field },
            Tsrv.url.getFunConfig
          ).then(r => {
            vue.prototype.$Loading.finish();
            const [res, err] = r;
            if (err !== undefined || !res.success) {
              // vue.prototype.$Message.error(err !== undefined ? err : res.msg);
              vue.prototype.$msg(err !== undefined ? err : res.msg);
              resolve(false);
            } else {
              if (res.data.data.length > 0) {
                const funConfig = res.data.data[0].fun_config; // layout
                const compConfig = res.data.data[0].fun_set; // compConf
                try {
                  let funObj: any = null;
                  let compObj: any = null;

                  if (!Tsrv.utils.noValue(funConfig)) {
                    funObj = JSON.parse(funConfig);
                    if (res.data.permission)
                      funObj = Tsrv.utils.configRecurse(
                        funObj,
                        res.data.permission,
                        'permission'
                      );
                    if (res.data.funI18nFields)
                      funObj = Tsrv.utils.configRecurse(
                        funObj,
                        res.data.funI18nFields,
                        'funI18nFields'
                      );
                    if (!Tsrv.noValue(res.data?.funLexicon)) {
                      const funLexicon = res.data.funLexicon;
                      const d = {};
                      funLexicon.forEach(el => {
                        d[el] = true;
                      });
                      funObj = Tsrv.utils.configRecurse(
                        funObj,
                        d,
                        'funLexicon'
                      );
                    }

                    if (res.data.audit)
                      funObj = Tsrv.utils.configRecurse(
                        funObj,
                        res.data.audit,
                        'audit'
                      );
                    if (res.data.funInfo)
                      funObj = Tsrv.utils.configRecurseSingle(
                        funObj,
                        res.data.funInfo.mainFun,
                        'mainFun'
                      );

                    this.context.commit('SET_LAYOUTCONFIGS', {
                      key: field,
                      val: funObj
                    });
                    this.context.commit('SET_FUNINFO', {
                      key: field,
                      val: res.data.funInfo
                    });
                  }
                  if (!Tsrv.utils.noValue(compConfig)) {
                    compObj = JSON.parse(compConfig);
                    if (
                      compObj.config &&
                      res.data.permission &&
                      res.data.permission[field]
                    )
                      compObj['config']['permission'] =
                        res.data.permission[field];
                    compObj['config']['funI18nFields'] =
                      res.data.funI18nFields[field];
                    if (!Tsrv.noValue(res.data?.funLexicon)) {
                      if (res.data.funLexicon.includes(field))
                        compObj['config']['funLexicon'] = true;
                    }
                    this.context.commit('SET_FUNCONFIGS', {
                      key: field,
                      val: compObj
                    });
                  }
                  if (
                    !Tsrv.utils.noValue(compObj) ||
                    !Tsrv.utils.noValue(funObj)
                  ) {
                    resolve({
                      current: val.type === 'layout' ? funObj : compObj,
                      all:
                        val.type === 'layout'
                          ? this.layoutConfigs
                          : this.funConfigs
                    });
                  } else {
                    resolve(true);
                  }
                } catch (e) {
                  console.error(e);
                  resolve(false);
                }
              }
            }
          });
        }
      } else {
        resolve(false);
      }
    });
  }
}
